<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>


    <!-- HTML结构 -->
    <form id="test-register" action="#" target="_blank" onsubmit="return checkRegisterForm()">
        <p id="test-error" style="color:red"></p>
        <p>
            用户名: <input type="text" id="username" name="username">
        </p>
        <p>
            口令: <input type="password" id="password" name="password">
        </p>
        <p>
            重复口令: <input type="password" id="password-2">
        </p>
        <p>
            <button type="submit">提交</button> <button type="reset">重置</button>
        </p>
    </form>
    <!-- 利用JavaScript检查用户注册信息是否正确，在以下情况不满足时报错并阻止提交表单：
        用户名必须是3-10位英文字母或数字；
        口令必须是6-20位；
        两次输入口令必须一致。 -->

    <script>
        function checkRegisterForm() {
            var name = document.getElementsById('username');
            var rex = /^\w{3,10}$/;
            var pwd = document.getElementsById('password');
            var pwd2 = document.getElementById('password-2')
            if ((rex.test(name.value) == true) && (pwd.values == pwd2.values) && (pwd.values.length>6) &&  (pwd.values.length<20)) {
                return true;
            }else{
                return false;
            }
        }
        // function checkRegisterForm() {
        //     var usrname = document.getElementById('username');
        //     var gz = /^[_0-9a-zA-Z]{3,10}$/;
        //     var pwd1 = document.getElementById('password');
        //     var pwd2 = document.getElementById('password-2');
        //     if (gz.test(usrname.value) == true && (pwd1.value.length > 6 && pwd1.value.length < 20) && (pwd1.value == pwd2.value)) {
        //         return true;
        //     } else {
        //         return false;
        //     }

        // }
        ; (function () {
            window.testFormHandler = checkRegisterForm;
            var form = document.getElementById('test-register');
            if (form.dispatchEvent) {
                var event = new Event('submit', {
                    bubbles: true,
                    cancelable: true
                });
                form.dispatchEvent(event);
            } else {
                form.fireEvent('onsubmit');
            }
        })();
        
    </script>
</body>

</html>